// 多组件库的国际化和本地项目国际化兼容
import { type I18n, createI18n } from "vue-i18n";
import type { App, WritableComputedRef } from "vue";
import { storageLocal, isObject } from "@pureadmin/utils";

// element-plus国际化
import enLocale from "element-plus/es/locale/lang/en";
import zhLocale from "element-plus/es/locale/lang/zh-cn";

import { load } from "js-yaml";

// 动态加载YAML文件
const loadYamlFile = async (path: string) => {
  try {
    const response = await fetch(path);
    const yamlText = await response.text();
    return load(yamlText);
  } catch (error) {
    console.error(`Failed to load YAML file: ${path}`, error);
    return {};
  }
};

// 缓存已加载的语言文件
const localeCache: Record<string, any> = {};

const siphonI18n = async (prefix = "zh-CN") => {
  if (localeCache[prefix]) {
    return localeCache[prefix];
  }
  const yamlPath = `/locales/${prefix}.yaml`;
  const localeData = await loadYamlFile(yamlPath);
  localeCache[prefix] = localeData;
  return localeData;
};

// 同步版本，用于初始化
const siphonI18nSync = (prefix = "zh-CN") => {
  // 提供默认的语言数据
  const defaultLocales = {
    "zh-CN": {
      login: {
        username: "用户名",
        password: "密码",
        login: "登录",
        loginBtn: "登录",
        loginSuccess: "登录成功",
        loginFail: "登录失败",
        usernameRequired: "请输入账号"
      },
      buttons: {
        login: "登录",
        logout: "退出系统",
        changePassword: "修改密码",
        confirm: "确认",
        cancel: "取消",
        save: "保存",
        edit: "修改",
        delete: "删除",
        add: "新增",
        search: "搜索",
        reset: "重置",
        refresh: "刷新",
        export: "导出",
        import: "导入",
        submit: "提交",
        back: "返回",
        close: "关闭",
        view: "查看",
        detail: "详情",
        enable: "启用",
        disable: "禁用",
        upload: "上传",
        download: "下载"
      },
      menus: {
        home: "首页",
        welcome: "欢迎页",
        system: "系统管理",
        user: "用户管理",
        role: "角色管理",
        menu: "菜单管理",
        dept: "部门管理",
        mytBase: "基础管理",
        device: "设备管理",
        channel: "渠道管理",
        dealer: "经销商管理",
        userManage: "用户管理",
        mytSystemManage: "系统管理",
        assetManage: "资产管理",
        eventManage: "事件管理",
        terminalManage: "终端管理",
        lessees: "租户管理",
        lesseesDetail: "租户详情",
        userClassify: "用户分类",
        systemSeed: "系统种子",
        errorPage: "异常页面",
        login: "登录",
        loading: "加载中..."
      },
      tags: {
        refresh: "刷新当前标签页",
        closeCurrent: "关闭当前标签页",
        closeLeft: "关闭左侧标签页",
        closeRight: "关闭右侧标签页",
        closeOther: "关闭其他标签页",
        closeAll: "关闭全部标签页",
        fullscreen: "内容区全屏",
        exitFullscreen: "内容区退出全屏"
      },
      common: {
        language: "语言",
        chinese: "中文",
        english: "English",
        systemConfig: "打开系统配置"
      }
    },
    en: {
      login: {
        username: "Username",
        password: "Password",
        login: "Login",
        loginBtn: "Login",
        loginSuccess: "Login successful",
        loginFail: "Login failed",
        usernameRequired: "Please enter username"
      },
      buttons: {
        login: "Login",
        logout: "Logout",
        changePassword: "Change password",
        confirm: "Confirm",
        cancel: "Cancel",
        save: "Save",
        edit: "Edit",
        delete: "Delete",
        add: "Add",
        search: "Search",
        reset: "Reset",
        refresh: "Refresh",
        export: "Export",
        import: "Import",
        submit: "Submit",
        back: "Back",
        close: "Close",
        view: "View",
        detail: "Detail",
        enable: "Enable",
        disable: "Disable",
        upload: "Upload",
        download: "Download"
      },
      menus: {
        home: "Home",
        welcome: "Welcome",
        system: "System Management",
        user: "User Management",
        role: "Role Management",
        menu: "Menu Management",
        dept: "Department Management",
        mytBase: "Base Management",
        device: "Device Management",
        channel: "Channel Management",
        dealer: "Dealer Management",
        userManage: "User Management",
        mytSystemManage: "System Management",
        assetManage: "Asset Management",
        eventManage: "Event Management",
        terminalManage: "Terminal Management",
        lessees: "Tenant Management",
        lesseesDetail: "Tenant Details",
        userClassify: "User Classification",
        systemSeed: "System Seed",
        errorPage: "Error Page",
        login: "Login",
        loading: "Loading..."
      },
      tags: {
        refresh: "Refresh Current Tab",
        closeCurrent: "Close Current Tab",
        closeLeft: "Close Left Tabs",
        closeRight: "Close Right Tabs",
        closeOther: "Close Other Tabs",
        closeAll: "Close All Tabs",
        fullscreen: "Content Fullscreen",
        exitFullscreen: "Exit Content Fullscreen"
      },
      common: {
        language: "Language",
        chinese: "中文",
        english: "English",
        systemConfig: "Open System Configuration"
      }
    }
  };
  return defaultLocales[prefix] || defaultLocales["zh-CN"];
};

export const localesConfigs = {
  zh: {
    ...siphonI18nSync("zh-CN"),
    ...zhLocale
  },
  en: {
    ...siphonI18nSync("en"),
    ...enLocale
  }
};

/** 获取对象中所有嵌套对象的key键，并将它们用点号分割组成字符串 */
function getObjectKeys(obj: any): Set<string> {
  const stack: any[] = [];
  const keys: Set<string> = new Set();

  stack.push({ obj, key: "" });

  while (stack.length > 0) {
    const { obj, key } = stack.pop();

    for (const k in obj) {
      const newKey = key ? `${key}.${k}` : k;

      if (obj[k] && isObject(obj[k])) {
        stack.push({ obj: obj[k], key: newKey });
      } else {
        keys.add(key);
      }
    }
  }

  return keys;
}

/** 将展开的key缓存 */
const keysCache: Map<string, Set<string>> = new Map();
const flatI18n = (prefix = "zh-CN") => {
  let cache = keysCache.get(prefix);
  if (!cache) {
    cache = getObjectKeys(siphonI18n(prefix));
    keysCache.set(prefix, cache);
  }
  return cache;
};

/**
 * 国际化转换工具函数（自动读取根目录locales文件夹下文件进行国际化匹配）
 * @param message message
 * @returns 转化后的message
 */
export function transformI18n(message: any = "") {
  if (!message) {
    return "";
  }

  // 处理存储动态路由的title,格式 {zh:"",en:""}
  if (typeof message === "object") {
    const locale: string | WritableComputedRef<string> | any =
      i18n.global.locale;
    return message[locale?.value];
  }

  const key = message.match(/(\S*)\./)?.input;

  if (key && flatI18n("zh-CN").has(key)) {
    return i18n.global.t.call(i18n.global.locale, message);
  } else if (!key && Object.hasOwn(siphonI18n("zh-CN"), message)) {
    // 兼容非嵌套形式的国际化写法
    return i18n.global.t.call(i18n.global.locale, message);
  } else {
    return message;
  }
}

/** 此函数只是配合i18n Ally插件来进行国际化智能提示，并无实际意义（只对提示起作用），如果不需要国际化可删除 */
export const $t = (key: string) => key;

export const i18n: I18n = createI18n({
  legacy: false,
  locale:
    (storageLocal().getItem("pure-admin-locale") as { locale?: string } | null)
      ?.locale ?? "zh",
  fallbackLocale: "en",
  messages: localesConfigs
});

export function useI18n(app: App) {
  app.use(i18n);
}
